package com.netty.nio;

import java.io.IOException;
import java.net.InetSocketAddress;
import java.nio.ByteBuffer;
import java.nio.channels.ServerSocketChannel;
import java.nio.channels.SocketChannel;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;

/**
 * @Date 2021/8/31 15:53
 * @Author WangLinBao
 * @Description
 */
public class NioServerSocket {

    public static List<SocketChannel> channelList = new ArrayList<>();
    public static void main(String[] args) throws IOException {
        ServerSocketChannel serverSocketChannel = ServerSocketChannel.open();
        //通过serverSocketChannel 中获取socket并且绑定到指定端口
        serverSocketChannel.socket().bind(new InetSocketAddress(9000));
        //nio非阻塞的关心在与设置configureBlocking false 非阻塞设置
        serverSocketChannel.configureBlocking(false);
        System.out.println("服务启动成功.....");
        while(true){//占用cpu   --->>优化思路 阻塞 让出cpu
            SocketChannel socketChannel = serverSocketChannel.accept();
            if(socketChannel!=null){
                System.out.println("连接成功.....");
                //将连接过来的客户端socketChannel也设置为非阻塞
                socketChannel.configureBlocking(false);
                //将客户的连接保存在list中
                channelList.add(socketChannel);
            }
            //遍历所有的客户端连接，并从连接中读取数据
            Iterator<SocketChannel> iterator = channelList.iterator();
            //全部遍及  即使没有read事件发生 ---> 将有事件channel放到单独的队列中
            while(iterator.hasNext()){
                SocketChannel sc = iterator.next();
                ByteBuffer byteBuffer = ByteBuffer.allocate(128);
                int len = sc.read(byteBuffer);
                if(len>0){
                    System.out.println("接收到客户端的信息: "+new String(byteBuffer.array()));
                }else if(len==-1){
                    iterator.remove();
                    System.out.println("客户端连接关闭...");
                }

            }


        }
    }
}
